<template>
  <div class="awsCenter">
    <div style="border: black 0px solid;width: 100%;height: 550px;display: flex;
flex-direction: column;
align-items: center;">
      <!--    按钮栏    -->
      <div class="awsCenter" style="width: 100%;height: 40px;border: black 0px solid">
        <el-select clearable v-model="specialty" placeholder="专业领域" style="width: 150px">
          <el-option
            v-for="item in specialtyList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select clearable v-model="room" placeholder="咨询室" style="width: 100px;margin-left: 10px">
          <el-option
            v-for="item in roomList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select clearable v-model="status" placeholder="状态" style="width: 100px;margin-left: 10px">
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-button @click="getCounselor(true)" style="width: 80px;margin-left: 10px" type="primary" plain>查询</el-button>
        <el-button style="width: 80px;margin-left: auto" type="primary" @click="showSave=true;sou=false;dialogTitle='咨询师信息';getSaveInfo()">新增</el-button>
        <el-button @click="delAll">批量删除</el-button>

      </div>


      <!--   表格    -->
      <el-table :data="tableData" stripe style="width: 100%;margin-top: 20px" @selection-change="selectCounselor" height="700px" :row-style="{ height: '80px' }">
        <el-table-column type="selection" width="55" />
        <el-table-column :disabled="true" prop="username" label="账号" width="130" />
        <el-table-column label="姓名" width="150">
          <template #default="scope">
            <el-popover effect="light" trigger="hover" placement="top" width="auto">
              <template #default>
                <div>姓名: {{ scope.row.realname }}</div>
                <div>个人简介: {{ scope.row.bio?scope.row.bio:'暂无' }}</div>
              </template>
              <template #reference>
                <el-tag>{{ scope.row.realname }}</el-tag>
              </template>
            </el-popover>
          </template>
        </el-table-column>
<!--        <el-table-column prop="room" label="咨询室" width="120px"/>-->
        <el-table-column prop="specialty" label="专业领域" width="120px"/>
        <el-table-column prop="time" label="工作时间" width="180px">
          <template #default="{ row }">
            <el-button link type="primary" @click="showTimes(row)">点击查看</el-button>
          </template>
        </el-table-column>
        <el-table-column label="评分" width="120">
          <template #default="scope">
            <el-tag type="warning">{{ formatToTwoDecimalPlaces(scope.row.rating) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" >
          <template #default="scope">
            <el-tag :type="checkType(scope.row.status)">{{ scope.row.status=='1'?'启用':'禁用'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" plain :icon="Edit" circle @click="sou=true;showSave=true;dialogTitle='修改信息';handleUpdate(row);" />
            <el-button type="danger" plain :icon="Delete" circle @click="handleDelete(row)" />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页条 -->
      <div  class="demo-pagination-block">
        <el-pagination
          style="margin-top: 20px"
          v-model:current-page="currentPage"
          :page-size="8"
          :size="size"
          :disabled="disabled"
          :background="background"
          layout="total, prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div>


      <el-dialog
        @close="cleanForm"
        :destroy-on-close="true"
        v-model="showSave"
        :title="dialogTitle"
        width="800"
        align-center
        :close-on-click-modal="false"

      >
        <el-form style="height: 440px;overflow: auto;" :model="counselorForm" label-position="top" label-width="100px">
          <el-tabs v-model="counselorClass" >
            <el-tab-pane label="基本信息" name="base">
              <el-form-item prop="username" label-position="top" label="账号">
                <el-select :disabled="isUp" v-model="counselorForm.username" placeholder="请选择" style="width: 240px">
                  <el-option
                    v-for="item in usernameList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item prop="specialty" label-position="top" label="选择专业领域">
                <el-select v-model="counselorForm.specialty" placeholder="请选择" style="width: 240px">
                  <el-option
                    v-for="item in specialtyList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item prop="bio" label-position="top" label="个人简介">
                <el-input v-model="counselorForm.bio" placeholder="请输入" style="width: 400px"
                          :rows="4"
                          type="textarea" >

                </el-input>
              </el-form-item>
              <el-form-item prop="status" label="启用状态">
                <el-switch v-model="counselorForm.status" active-text="启用" inactive-text="停用" active-value="1" inactive-value="0" />
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="工作时间" name="time">
              <div style="width: 100%;display: flex">
                <el-button style="margin-left: auto" @click="addRow" plain type="primary">增行</el-button>
              </div>
              <el-table :data="timeRows" style="width: 100%;height: 270px;overflow-y: auto;">
                <el-table-column width="180" label="咨询室">
                  <template v-slot="{ row }">
                    <el-select v-model="row.room" placeholder="请选择" style="width: 150px">
                      <el-option
                        v-for="item in roomList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column width="180" label="工作日">
                  <template v-slot="{ row }">
                    <el-select v-model="row.weekend" placeholder="请选择" style="width: 150px">
                      <el-option
                        v-for="item in weekendList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column width="300" label="工作时间">
                  <template v-slot="{ row }">
                    <div style="display: flex;flex-direction: row">
                      <div>
                        <el-time-select
                          format="HH:mm:ss"
                          v-model="row.starttime"
                          style="width: 130px"
                          :max-time="row.endtime"
                          class="mr-4"
                          placeholder="开始时间"
                          start="08:30"
                          step="00:15"
                          end="18:30"
                        />
                      </div>
                      <div style="margin-left: 10px">
                        <el-time-select
                          format="HH:mm:ss"
                          v-model="row.endtime"
                          style="width: 130px"
                          :min-time="row.starttime"
                          placeholder="结束时间"
                          start="08:30"
                          step="00:15"
                          end="18:30"
                        />
                      </div>
                    </div>

                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template v-slot="{ row, $index }">
                    <el-button  type="danger" circle plain :icon="Delete" @click="deleteRow($index)"></el-button>
                  </template>
                </el-table-column>
              </el-table>

            </el-tab-pane>
          </el-tabs>


        </el-form>

        <template #footer>
          <div style="margin-top: -20px">
            <el-button @click="showSave = false">取 消</el-button>
            <el-button type="primary" @click="saveOrUpdate">
              确 认
            </el-button>
          </div>
        </template>
      </el-dialog>


      <el-dialog
        @close="cleanTimeForm"
        :destroy-on-close="true"
        v-model="showTime"
        title="工作时间"
        width="800"
        align-center
        :close-on-click-modal="false"
      >
        <div style="padding: 20px;height: 400px">
          <el-form label-position="top" label-width="100px">

            <el-tabs v-model="time">
              <el-tab-pane label="工作时间" name="times">
                <el-table :data="timeForm" style="width: 100%;height: 270px;overflow-y: auto;">
                  <el-table-column width="180" label="咨询室">
                    <template v-slot="{ row }">
                      <el-select disabled v-model="row.room" placeholder="请选择" style="width: 150px">
                        <el-option
                          v-for="item in roomList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column width="180" label="工作日">
                    <template v-slot="{ row }">
                      <el-select disabled v-model="row.weekend" placeholder="请选择" style="width: 150px">
                        <el-option
                          v-for="item in weekendList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="开始时间">
                    <template v-slot="{ row }">
                      <el-time-picker disabled v-model="row.starttime" placeholder="选择开始时间" style="width: 100%" />
                    </template>
                  </el-table-column>
                  <el-table-column label="结束时间">
                    <template v-slot="{ row }">
                      <el-time-picker disabled v-model="row.endtime" placeholder="选择结束时间" style="width: 100%" />
                    </template>
                  </el-table-column>
                </el-table>

              </el-tab-pane>

            </el-tabs>

          </el-form>
        </div>


      </el-dialog>
    </div>
  </div>


</template>

<script lang="ts" setup>
import {
  delCounselorService,
  getByUserIdService,
  getCounselorService,
  getUsernameService,
  saveCounselorService, upCounselorService
} from '@/api/counselor.js'
import {getRoom} from '@/api/room.js'
import {onMounted, ref} from "vue";
import {Delete, Edit} from "@element-plus/icons-vue";
import moment from "moment/moment";
import {getUserClientService, getWorkTimeService} from "@/api/user.js";
import {ComponentSize, ElMessage, ElMessageBox} from "element-plus";
import {getTimeslotById} from "@/api/timeslot.js";

const time=ref('times')
const timeForm=ref([])

const showTime=ref(false)

const showTimes=(async (row)=>{
  //查询当前时间段并且渲染
  console.log(row)
  let res=await getWorkTimeService(row.userid)
  if (res.code===200){
    let list=res.data
    list.forEach(item=>{

    })
    timeForm.value=list
  }

  showTime.value=true
})

function formatToTwoDecimalPlaces(num) {
  if (num){
    return Number(num).toFixed(2);
  }else{
    return '暂无'
  }

}

const currentPage = ref(1)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)

const specialty=ref('')
const room=ref('')
const status=ref('')

const total=ref(0)


const roomList = ref([])
const statusList=[
  {
    value: '1',
    label: '启用',
  },
  {
    value: '0',
    label: '禁用',
  }
]

const specialtyList=[
  {
    value: '心理健康',
    label: '心理健康',
  },
  {
    value: '婚姻和家庭',
    label: '婚姻和家庭',
  },{
    value: '职业发展',
    label: '职业发展',
  },
  {
    value: '教育和学术',
    label: '教育和学术',
  },
  {
    value: '健康和营养',
    label: '健康和营养',
  }
]

const tableData=ref([])

onMounted(async ()=>{
  //页面挂载渲染表格
  let res=await getCounselorService(getData.value)
  console.log(res)
  if (res.code===200){
    tableData.value=res.data.data
    total.value = res.data.total
  }

  //页面挂载渲染所有咨询室
  const resRoom=await getRoom()
  if (resRoom.code===200){
    resRoom.data.forEach(item=>{
      roomList.value.push({
        value: item.room,
        label: item.room,
      })
    })
  }
})



const getData=ref({
  current:currentPage.value,
  pageSize:8,
  specialty:'',
  room:'',
  status:''
})

const getCounselor=(async (tag)=>{
  getData.value = {
    current: currentPage.value,
    pageSize: 8,
    specialty: specialty.value,
    room: room.value,
    status: status.value
  }
  console.log(getData.value)
  let res = await getCounselorService(getData.value)
  if (res.code === 200) {
    if (tag){
      ElMessage.success("查询成功")
    }
    tableData.value = res.data.data
    total.value = res.data.total
  }
})


const handleCurrentChange = async (val: number) => {
  getData.value = {
    current: val,
    pageSize: 8,
    specialty: specialty.value,
    room: room.value,
    status: status.value
  }
  let res = await getCounselorService(getData.value)
  if (res.code === 200) {
    tableData.value = res.data.data
    total.value = res.data.total
  }
}

//表单数据
const counselorForm=ref({
  username:'',
  specialty:'',
  bio:'',
  status:'1',
  counselorscheduleList:[]
})

const cleanForm=(()=>{
  counselorForm.value={
    username:'',
    specialty:'',
    bio:'',
    status:'1',
    counselorscheduleList:[]
  }
  timeRows.value=[]
  counselorClass.value='base'
  usernameList.value=[]

  isUp.value=false
})

const usernameList=ref([])

//新增咨询室信息
const showSave=ref(false)
const dialogTitle=ref('')

const getSaveInfo=(async ()=>{
  //新增时渲染表单数据
  const resUsername=await getUsernameService()
  if (resUsername.code===200){
    resUsername.data.forEach(item=>{
      usernameList.value.push({
        label:item.username,
        value:item.username
      })
    })
  }

})

const checkType=((status)=>{
  if (status=='1'){
    return 'success'
  }else {
    return 'error'
  }
})

//时间转换
function convertStringToTime(timeString) {
  // 获取当前日期
  const currentDate = moment().format('ddd MMM DD YYYY');

  // 合并日期和时间字符串
  const dateTimeString = `${currentDate} ${timeString} GMT+0800 (中国标准时间)`;

  // 使用 moment.js 将日期时间字符串转换为 Date 对象
  const dateObject = moment(dateTimeString, "ddd MMM DD YYYY HH:mm:ss [GMT]Z (z)").toDate();

  return dateObject;
}

const saveCounselor=(async ()=>{

  if (counselorForm.value.username&&counselorForm.value.specialty){

    //如填了时间

    if (timeRows.value.length!=0){
      //校验和转换
      if (checkTimes()){
        counselorForm.value.counselorscheduleList=timeRows.value
        console.log(counselorForm.value)
        let res=await saveCounselorService(counselorForm.value)
        if (res.code===200){
          ElMessage.success(res.message)
          //重新渲染
          await getCounselor(false)
          timeRows.value.forEach(item=>{
            item.starttime=item.starttime.toString().split(' ')[4]
            item.endtime=item.endtime.toString().split(' ')[4]
          })
          showSave.value=false
        }else {
          timeRows.value.forEach(item=>{
            item.starttime=item.starttime.toString().split(' ')[4]
            item.endtime=item.endtime.toString().split(' ')[4]
          })
          ElMessage.warning(res.errMsg)
        }
      }
    }else {
      timeRows.value.forEach(item=>{
        item.starttime=item.starttime.toString().split(' ')[4]
        item.endtime=item.endtime.toString().split(' ')[4]
      })
      ElMessage.warning("请填写工作时间")
    }

  }else {
    timeRows.value.forEach(item=>{
      item.starttime=item.starttime.toString().split(' ')[4]
      item.endtime=item.endtime.toString().split(' ')[4]
    })
    ElMessage.warning("请填写完整")
  }
})

//检查时间表单
const checkTimes=(()=>{

  for(let i = 0; i < timeRows.value.length;i++) {
    if (!timeRows.value[i].room||!timeRows.value[i].weekend||!timeRows.value[i].starttime||!timeRows.value[i].endtime){
      ElMessage.warning("工作时间未填写完整")
      return false;
    }else {
      //时间转换
      timeRows.value[i].starttime=convertStringToTime(timeRows.value[i].starttime)
      timeRows.value[i].endtime=convertStringToTime(timeRows.value[i].endtime)
    }
  }
  return true;
})



const sou=ref(false)

//修改咨询师信息
const handleUpdate=(async (row)=>{
  let res=await getByUserIdService(row.userid)
  console.log(res)
  if (res.code===200){
    counselorForm.value.username=res.data.username
    counselorForm.value.bio=res.data.bio
    counselorForm.value.specialty=res.data.specialty
    counselorForm.value.status=res.data.status
    res.data.counselorscheduleList.forEach(item=>{
      timeRows.value.push({
        room: item.room,
        weekend: item.weekend,
        starttime: item.starttime.toString().split(' ')[3],
        endtime:item.endtime.toString().split(' ')[3]
      })
    })

    isUp.value=true
  }
})

const isUp=ref(false)
const saveOrUpdate=(async ()=>{
  if (!sou.value) {
    //新增
    await saveCounselor()
  }else {
    //修改

    if (counselorForm.value.username&&counselorForm.value.specialty){
      //如填了时间
      if (timeRows.value.length!=0){
        //校验和转换
        if (checkTimes()){
          counselorForm.value.counselorscheduleList=timeRows.value
          console.log(counselorForm.value)
          let res=await upCounselorService(counselorForm.value)
          if (res.code===200){
            ElMessage.success(res.message)
            //重新渲染
            await getCounselor(false)
            timeRows.value.forEach(item=>{
              item.starttime=item.starttime.toString().split(' ')[4]
              item.endtime=item.endtime.toString().split(' ')[4]
            })

            showSave.value=false
          }else {
            timeRows.value.forEach(item=>{
              item.starttime=item.starttime.toString().split(' ')[4]
                item.endtime=item.endtime.toString().split(' ')[4]
            })
            ElMessage.warning(res.errMsg)
          }
        }
      }else {
        timeRows.value.forEach(item=>{
          item.starttime=item.starttime.toString().split(' ')[4]
          item.endtime=item.endtime.toString().split(' ')[4]
        })
        ElMessage.warning("请填写工作时间")
      }

    }else {
      timeRows.value.forEach(item=>{
        item.starttime=item.starttime.toString().split(' ')[4]
        item.endtime=item.endtime.toString().split(' ')[4]
      })
      ElMessage.warning("请填写完整")
    }



  }
})



//删除
//批量删除
const selected=ref([])
function selectCounselor(selectedRows) {
  selected.value=selectedRows
}

const delAll=(async ()=>{
  if (selected.value.length==0){
    ElMessage.warning("请先选择数据")
  }else {
    await ElMessageBox.confirm(
      '您确定要删除吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {

      // 执行删除操作
      dels()
      //重新渲染
      getCounselor()

    }).catch((err) => {
      console.log(err)
    });
  }

})

const dels=(async ()=>{
  console.log(selected.value)
  let res=await delCounselorService(selected.value)
  if (res.code===200){
    ElMessage.success(res.message)
  }else {
    ElMessage.warning(res.errMsg)
  }
})

//单个删除
const handleDelete=((row)=>{
  let list=[]
  list.push(row)
  ElMessageBox.confirm(
    '您确定要删除吗？',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {

    let res=await delCounselorService(list)
    if (res.code===200){
      ElMessage.success(res.message)
      await getCounselor()
    }else {
      ElMessage.warning(res.errMsg)
    }

  }).catch((err) => {
    console.log(err)
  });
})



const counselorClass=ref('base')

const weekendList = ref([
  {
    label: '星期一',
    value: '1'
  },
  {
    label: '星期二',
    value: '2'
  },
  {
    label: '星期三',
    value: '3'
  },
  {
    label: '星期四',
    value: '4'
  },
  {
    label: '星期五',
    value: '5'
  }
])

const timeRows = ref([
]);

const addRow = () => {
  timeRows.value.push({
    room: '',
    weekend: '',
    starttime: '',
    endtime:''
  });
};

const deleteRow = (index: number) => {
  timeRows.value.splice(index, 1);
};


</script>

<style>
.awsCenter{
  display: flex;
  align-items: center;
}
</style>
